package cn.tm.ms.nerver.idempotent.storage.impl;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

import cn.tm.ms.nerver.common.SystemClock;
import cn.tm.ms.nerver.idempotent.storage.IStorage;
import cn.tm.ms.nerver.idempotent.support.AbstractIdempotent;

/**
 * 基于Map存储幂等数据
 * 
 * @author lry
 */
public class MemoryMapStorage extends AbstractIdempotent implements IStorage {

	/**
	 * 最大容量
	 */
	public static final int MAX_CAPACITY = 10000;
	
	/**
	 * 持久库
	 */
	private ConcurrentHashMap<String, AtomicLong> idempotents;

	public MemoryMapStorage() {
		if (idempotents == null) {
			idempotents = new ConcurrentHashMap<String, AtomicLong>(MAX_CAPACITY);
		}
	}
	
	/**
	 * 初始化
	 */
	public void init(long timeWindow) throws Throwable {
		super.init(timeWindow);
	}

	/**
	 * 校验KEY值是否存在
	 */
	public boolean containsKey(String key) {
		return idempotents.containsKey(key);
	}

	/**
	 * 获取值
	 */
	public long get(String key) {
		return idempotents.get(key).get();
	}

	/**
	 * 存放操作
	 */
	public void put(String key, long time) {
		idempotents.put(key, new AtomicLong(time));
	}

	/**
	 * 清理
	 */
	public void cleanup() {
		if (idempotents == null) {
			for (Map.Entry<String, AtomicLong> entry : idempotents.entrySet()) {
				long nowTime = SystemClock.now();// 当前时间
				long expireTime = entry.getValue().get() + super.timeWindow;// 到期时间
				if (nowTime > expireTime) {// 过期清理
					idempotents.remove(entry.getKey());
				}
			}
		}
	}

	/**
	 * 销毁
	 */
	public void destroy() {
		super.destroy();
		if (idempotents == null) {
			idempotents.clear();
		}
	}
	
	/**
	 * 设置持久库
	 */
	protected IStorage getStorage() {
		return this;
	}

}
